<script setup lang="ts">
import PageSkeleton from '../index/components/PageSkeleton.vue'
import { getHomebannerAPI, getHomeCategoryAPI, getHotPanelAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CustomNavbar from '@/components/CustomNavbar.vue'
import CategoryPanel from '@/components/CategoryPanel.vue'
import HotPanel from '@/components/HotPanel.vue'
import { ref, type XtxGuessInstance } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const bannerList = ref<BannerItem[]>([]) //保存轮播图数据
const categoryList = ref<CategoryItem[]>([])
const hotPanelList = ref<HotItem[]>([]) //存储热门推荐的数据
const guessRef = ref<XtxGuessInstance>()
const isLoading = ref(false)
// 是否触发下拉刷新
const isTriggered = ref(false)
// 获取轮播图数据
const getHomebannerData = async () => {
  const res = await getHomebannerAPI()
  // console.log(res)
  bannerList.value = res.result
}
// 获取前台分类的接口函数
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  // console.log(res)
  categoryList.value = res.result
}
// 获取前台热门推荐的数据
const getHotPanelList = async () => {
  const res = await getHotPanelAPI()
  // console.log(res)
  hotPanelList.value = res.result
}
// 猜你喜欢的数据
const OnScrolltolower = async () => {
  // 重置数据
  guessRef.value?.getMore()
  // console.log('滚动到底辣')
}
// 下拉刷新
async function onRrefresherrefresh() {
  // 开启动画
  isTriggered.value = true
  guessRef.value?.resetData()
  await Promise.all([getHomebannerData(), getHomeCategoryData(), getHotPanelList()])
  // 关闭动画
  isTriggered.value = false
}

// 页面加载
onLoad(() => {
  isLoading.value = true
  Promise.all([getHomebannerData(), getHomeCategoryData(), getHotPanelList()])
  isLoading.value = false
})
</script>

<template>
  <PageSkeleton v-if="isLoading" />
  <custom-navbar></custom-navbar>
  <scroll-view
    refresher-enabled
    @scrolltolower="OnScrolltolower"
    @refresherrefresh="onRrefresherrefresh"
    :refresher-triggered="isTriggered"
    scroll-y
  >
    <XtxSwiper :list="bannerList" />
    <CategoryPanel :list="categoryList" />
    <HotPanel :list="hotPanelList" />
    <!-- 猜你喜欢 -->
    <XtxGuess ref="guessRef" />
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7ff;
  display: flex;
  height: 100%;
  flex-direction: column;
}
</style>
